var wxpay = require('../../../utils/pay.js');
var util = require('../../../utils/util.js');
var app = getApp();
Page({
  data: {
    curAddressData: null,//收货地址
    storeid: app.globalData.storeId,
    showAdress : true, // false自提, true 非自提
    remark: '',
    remark2: '',
    remark3: '',
    cartResult: [],
    cutType: 0,//优惠方式1优惠券2折扣卡3余额
    money: 0,//配送费
    free: 0,//满多少免费
    packagMoney: 0,//包装费
    miniMoney: 0,//最低起送
    cardInfo: {},
    cuttypeList: {},
    couponid: 0,
    couponmoney: 0,
    showCouponList: false,
    showCarditemList: false,
    cardType: 1,//1充值卡4玖玖卡5福鲤卡
    proSumMoney: 0,
    proAndLimitMoney: 0,
    payMoney: 0,
    discount: 0,//折扣卡折扣
    carditemMoney: 0,//充值卡余额
    carditemDiscount: 0,
    carditemId: 0,
    couponList: [],
    coupon_isopen: 0,
    card_isopen: 0,
    carditem_isopen: 0,
    succDeset: false,//成功请求配送设置
    universalCard: 2,//0没买过玖玖通用卡，1已买通用卡
    seleGif: true,
    saleUid: 0, //销售员id
    jump: 0,    //0普通订单, 12 带货订单 
    createUid: 0
  },
  changeUseCard: function () {
    this.setData({
      seleGif: !this.data.seleGif
    })
  },

  getJJKInfo: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Coupon/GetCardExists?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            universalCard: res.data.Data ? 1 : 0
          })
        } else {
          util.showModal(res.data.Message);         
        }
      }
    })
  },


  //选择取货方式
  selectType: function (e) {
    let that = this;
    let showAdress = that.data.showAdress;
    let shipInfo = wx.getStorageSync('shipInfo');  
    if(!showAdress && shipInfo && !shipInfo.showAddress){
      wx.showToast({title: '只能选自提方式',icon: 'none'});
      return; 
    }
    that.setData({
      showAdress: ! showAdress
    })
    that.caculater();
  },
  // 选择优惠方式
  selectCuttype: function (e) {
    let cuttype = e.currentTarget.dataset.cuttype;
    let type = this.data.cutType;
    let showCouponList = this.data.showCouponList;
    if (cuttype == type) {
      cuttype = 0;
    }
    if (cuttype == 1) {
      showCouponList = true;
    }
    this.setData({
      cutType: cuttype,
      showCouponList: showCouponList
    })
    if (cuttype != 1) {
      this.caculater();
    }
  },
  chooseCouponNew: function (e) {
    let that = this;
    let couponid = e.currentTarget.dataset.couponid;
    let ordermoney = e.currentTarget.dataset.ordermoney;
    let couponmoney = e.currentTarget.dataset.money;
    let proSumMoney = parseFloat(that.data.proSumMoney);//商品总额
    if (proSumMoney < ordermoney) {
      wx.showToast({
        title: '不满足满减条件',
        mask: true
      })
      that.setData({
        cutType: 0
      })
      return;
    }else {
      that.data.couponmoney = couponmoney;
      that.setData({
        couponid: couponid
      })
    }
  },
  updateCouponId: function () {
    if (this.data.couponid) {
      this.caculater();
    } else {
      wx.showToast({
        title: '请选择优惠券',
        mask: true
      })
      this.setData({
        cutType: 0
      })
    }
    this.closeCoupon();
  },

  closeCoupon: function () {
    let couponid = this.data.couponid;
    let cutType = this.data.cutType;
    if(couponid == 0){
      cutType = 0;
    }
    this.setData({
      showCouponList: false,
      cutType: cutType
    })
  },

  // 弹出选择充值卡
  selectCardItem: function () {
    this.setData({
      showCarditemList: true,
      cutType: 3
    })
  },

  chooseCarditem: function (e) {
    let id = e.currentTarget.dataset.id;
    this.setData({
      carditemId: id
    })
  },

  closeCarditem: function () {
    this.setData({
      showCarditemList: false
    })
  },

  // 选择充值卡
  updateCardItemid: function () {
    this.caculater();
    this.closeCarditem();
  },

  // 计算商品总额（商品金额+配送费+包装费）和应付金额
  caculater: function () {
    let that = this;
    let showAdress = that.data.showAdress;//false自提true非自提
    let cuttype = that.data.cutType;//优惠方式
    let proSumMoney = parseFloat(that.data.proSumMoney);//商品总额
    let proAndLimitMoney = parseFloat(that.data.proAndLimitMoney);//商品金额+配送费+包装费
    let payMoney = parseFloat(that.data.payMoney);//应付金额
    let discount = that.data.discount;//折扣卡折扣
    let carditemMoney = parseFloat(that.data.carditemMoney);//充值卡余额
    let carditemDiscount = parseFloat(that.data.carditemDiscount);//充值卡支付比例
    let packMoney = parseFloat(that.data.packagMoney);//包装费
    let shipMoney = parseFloat(that.data.money);//配送费
    let cuttypeList = that.data.cuttypeList;
  
    if (!showAdress) {//计算配送费
      shipMoney = 0;
    }
    proAndLimitMoney = proSumMoney + packMoney + shipMoney;//商品金额+包装费+配送费

    if (cuttype == 0) {
      payMoney = proSumMoney + packMoney + shipMoney;
    }
    if (cuttype == 1) {//优惠券
      let couponmoney = that.data.couponmoney;
      payMoney = proSumMoney - couponmoney + packMoney + shipMoney;
    }
    if (cuttype == 2) {//折扣卡
      payMoney = proSumMoney * parseFloat(discount * 0.1) + packMoney + shipMoney;
    }
    if (cuttype == 3) {//充值卡
      let carditemList = cuttypeList.carditem;
      let cutCardItemMoney = proSumMoney * parseFloat(carditemDiscount * 0.01);
      for (let i = 0; i < carditemList.length; i++) {
        if (carditemList[i].Cid == that.data.carditemId) {
          carditemMoney = carditemList[i].Balance;
          cutCardItemMoney = parseFloat(proSumMoney * carditemList[i].Discount * 0.01); //使用充值卡抵扣金额
          if (carditemList[i].CardType == 5) {//福鲤卡
            payMoney = packMoney + shipMoney;
            if (cutCardItemMoney > carditemMoney) {//余额不足
              payMoney = parseFloat(cutCardItemMoney) - parseFloat(carditemMoney) + packMoney + shipMoney;
            }
          } else {
            if (carditemMoney > cutCardItemMoney) {//余额充足
              payMoney = proSumMoney - parseFloat(cutCardItemMoney) + packMoney + shipMoney;
            } else {
              payMoney = proSumMoney - carditemMoney + packMoney + shipMoney;
            }
          }    
        }
        if (payMoney < 0) {
          payMoney = 0;
        }
      }
    }
    that.setData({
      carditemMoney: carditemMoney,
      cutType: cuttype,
      proAndLimitMoney: parseFloat(proAndLimitMoney).toFixed(2),
      payMoney: parseFloat(payMoney).toFixed(2)
    })
  },

  // 获取外卖设置
  getDeliverySet: function () {
    let that = this;
    let recordIds = '';
    let said = that.data.curAddressData != null ? that.data.curAddressData.SAId : 0;
    let cartResult = that.data.cartResult;
    for (let i = 0; i < cartResult.length; i++) {
      recordIds += recordIds !='' ? ',': '';
      recordIds += cartResult[i].OrderProductInfo.RecordId;
    }
    if(recordIds=='' || !that.data.showAdress) return;
    wx.request({
      url: app.globalData.host + '/api/Ship/GetCartShip?recordIds=' + recordIds + '&said=' + said,
      success: function (res) {
        if (res.data.Code == 0) {
          let item = res.data.Data.Config;           
          if (item) {         
            that.setData({              
              free: item.FreeLimit,//满多少免费
              packagMoney: item.PackMoney,//包装费
              miniMoney: item.MinLimit,//最低起送
            })
          } 
          that.setData({
            succDeset: true,
            money: res.data.Data.ShipFee,  //配送费
          })                                 
          that.caculater();
        } else {
          util.showModal(res.data.Message);          
        }        
      }
    })
  },
  // 获取优惠方式
  getCutType: function (createUid) {
    let that = this;
    let paytype = "wechat";
    if(that.data.coupon_isopen == 0 && 
      that.data.card_isopen == 0 && 
      that.data.carditem_isopen == 0){
      return;
    }
    wx.request({
      url: app.globalData.host + '/api/coupon/GetDirectPromotion?uid=' + app.globalData.userInfo.Uid + '&createUid=' + createUid + '&paytype=' + paytype + '&promotionType=0',
      success: function (res) {
        if (res.data.Code == 0) {
          let cuttypeList = res.data.Data;
          let isBuy = res.data.Data.isBuy;
          let succDeset = that.data.succDeset;
          if (succDeset) {
            that.setCuttype(cuttypeList, isBuy);
          } else {
            that.defaultCardItem(cuttypeList, isBuy);
          }
        } else {          
          util.showModal(res.data.Message);
        }
      }
    })
  },
  setCuttype: function (cuttypeList, isBuy) {
    let that = this;
    let discount = 10;
    let carditemMoney = 0;
    let carditemDiscount = 0;
    let carditemId = 0;
    let cardType = 1;
    let couponList = [];
    if (that.data.card_isopen == 1 && cuttypeList.card) {
      discount = parseFloat(cuttypeList.card.Discount * 0.1).toFixed(1);
    }
    if (that.data.carditem_isopen == 1 && cuttypeList.carditem.length > 0) {
      let date = new Date();
      let cardItemInfo = cuttypeList.carditem[0];
      that.setData({
        cutType: 3
      })
      for (let i = 0; i < cuttypeList.carditem.length; i++) {
        var date2 = new Date(Date.parse(cuttypeList.carditem[i].ExpireTime.replace(/-/g, "/")));
        if (date2 < date) { //过期
          cuttypeList.carditem[i].isExpiretime = 1;
        } else {
          cuttypeList.carditem[i].isExpiretime = 0;
        }
        cuttypeList.carditem[i].ExpireTime = cuttypeList.carditem[i].ExpireTime.substr(0, 10);
      }
      for (let i = 0; i < cuttypeList.carditem.length; i++) {
        if (isBuy && cuttypeList.carditem[i].CardType == 4) {//已经有玖玖卡
          cardItemInfo = cuttypeList.carditem[i];
          that.setData({
            carditem_isopen: 1,
          })
          break;
        } else {
          if (cuttypeList.carditem[i].Balance > cardItemInfo.Balance) {
            cardItemInfo = cuttypeList.carditem[i];
          }
        }
      }
      carditemMoney = cardItemInfo.Balance;
      carditemDiscount = cardItemInfo.Discount;
      carditemId = cardItemInfo.Cid;
      cardType = cardItemInfo.CardType;

    }
    if (that.data.coupon_isopen == 1 && cuttypeList.coupon.length > 0) {
      couponList = cuttypeList.coupon;
    }
    that.data.cardType = cardType;
    that.setData({
      cuttypeList: cuttypeList,
      discount: discount,
      carditemMoney: carditemMoney,
      carditemDiscount: carditemDiscount,
      carditemId: carditemId,
      couponList: couponList
    })
    that.caculater();
  },

  // 第一次默认使用余额
  defaultCardItem: function (cuttypeList, isBuy) {
    let that = this;
    setTimeout(function () {
      that.setCuttype(cuttypeList, isBuy);
    }, 1000)
  },

  getInfo: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Staff/GetStaffIdByUid?uid=' + that.data.createUid,
      success: function (res) {
        if (res.data.Code == 0) {
          that.getPromition(res.data.Data.Id, res.data.Data.Uid);
          that.setData({
            cardInfo: res.data.Data
          })
        }
      }
    })
  },
  getPromition: function (cardid, createuid) {
    let that = this;
    let coupon_isopen = 0;
    let card_isopen = 0;
    let carditem_isopen = 0;
    wx.request({
      url: app.globalData.host + '/api/Staff/GetPromotion?staffId=' + cardid,
      success: function (res) {
        if (res.data.Code == 0) {
          let items = res.data.Data;
          for (let i = 0; i < items.length; i++) {
            if (items[i].Name == "coupon") {
              coupon_isopen = items[i].IsOpen;
            }
            if (items[i].Name == 'discount_card') {
              card_isopen = items[i].IsOpen;
            }
            if (items[i].Name == "card_item") {
              carditem_isopen = items[i].IsOpen;
            }
          }
          that.setData({
            coupon_isopen: coupon_isopen,
            card_isopen: card_isopen,
            carditem_isopen: carditem_isopen
          })
          that.getCutType(createuid);
        } else {         
          util.showModal(res.data.Message);
        }
      }
    })
  },

  onShow: function (e) {
    let that = this;
    that.initShippingAddress();
    if (app.globalData.userInfo) {
      that.getJJKInfo();
    } else {
      setTimeout(function () {
        that.onShow();
      }, 1000)
    }
  },

  onLoad: function (e) {
    var that = this;
    var cardId = wx.getStorageSync("cardId");
    var shipInfo = wx.getStorageSync('shipInfo');    
    var pages = getCurrentPages();
    var cartPage = pages[pages.length -2];    //上一个页面的引用
    that.setData({
      cartResult:  cartPage.data.cartResult,
      proSumMoney: e.sumprice,
      createUid: e.createUid,         //商家ID
      saleUid: e.saleUid
    });
    
    that.getInfo();
    if(shipInfo && !shipInfo.showAddress){
      that.selectType();                  //排队点餐，配送都是自提
    }
  },
  // 解码
  decodeUnicode: function (str) {
    str = str.replace(/\\/g, "%");
    return unescape(str);
  },

  // 立即付款
  createOrder: function () {
    var that = this;
    var uid = app.globalData.userInfo.Uid // 用户登录 uid
    if (!uid) {
      util.showModal('获取用户信息失败');
      return;
    }
    let sellist = '';
    let cartResult = that.data.cartResult;
    for (let i = 0; i < cartResult.length; i++) {
      sellist += '0_' + cartResult[i].OrderProductInfo.Pid + ',';
    }
    var said = 0;
    var remark = that.data.remark; // 备注信息
    var remark2 = that.data.remark2; // 联系人
    var remark3 = that.data.remark3; // 手机号
    var isPack = wx.getStorageSync('shipInfo') ? 0 : 1; //0 无包装费, 1 含包装费
    if (that.data.showAdress) {//非自提
      remark2 = "";
      remark3 = "";
      if (that.data.curAddressData == null || !that.data.curAddressData.SAId) {
        util.showModal('请填写地址信息'); return;
      } else {
        said = that.data.curAddressData.SAId;
      }
    }
    else {//自提
      said = 0;
      if (remark3 != "") {
        if (!util.vailPhone(remark3)) {
          util.showModal('请输入正确的手机号！'); return;
        }
      }
    }

    let proSumMoney = parseFloat(that.data.proSumMoney);
    let CardDiscountMoney = 0;
    let cutType = that.data.cutType;
    if (cutType == 2) {
      CardDiscountMoney = proSumMoney * (1 - that.data.discount * 0.1);
    }
    let tagindex = 4;
    if (app.globalData.userInfo.Uid == that.data.cardInfo.Uid) {
      tagindex = 1;
    }
    let CardItemId = cutType == 3 ? that.data.carditemId : 0;
    var postData = {
      Uid: app.globalData.userInfo.Uid,
      SaId: said,//配送地址id
      SelList: sellist, //'0_583674',//选中的购物车项键列表
      BuyerRemark: remark,//备注
      CreateUid: that.data.cardInfo.Uid,
      CardDiscountMoney: parseFloat(CardDiscountMoney).toFixed(2),
      CardItemId: CardItemId,
      PackMoney: that.data.packagMoney,
      Mobile: remark3,
      Consignee: remark2,
      CouponIdList: that.data.couponid,
      SaleUid: that.data.saleUid,
      Jump: that.data.jump,
      IsPack: isPack
    }

    //供货商家id
    let supplyUid = wx.getStorageSync('supplyUid');    
    let version = wx.getStorageSync('supplyVersion'); 
    if(supplyUid){
      postData.Jump = version == 5 ? 12 : 13;   //jump: 12 云点单, 13 云代货
      postData.CreateUid = supplyUid;
    }
    
    wx.showLoading({title: '提交中',mask: true})
    wx.request({
      url: app.globalData.host + '/api/order/SubmitOrderV2',
      method: 'POST',
      data: postData, // 设置请求的 参数
      success: (res) => {
        wx.hideLoading();
        if (res.data.Code != 0) {
          util.showModal(res.data.Message);
          return;
        } else {
          var oid = res.data.Data;
          let url = '/merchant/merchants/myCardCoupon/index?tagindex=' + tagindex;
          if (oid == 0) {
            wx.showToast({title: '支付成功',duration: 1000})
            wx.reLaunch({url: url,})
          } else {
            let receiveCard = 0;
            let universalCard = that.data.universalCard;
            if (universalCard == 0 && that.data.seleGif) {
              receiveCard = 1;
            }
            //代卖订单
            if(supplyUid){
              wxpay.wxpayWm(app, oid, url, receiveCard);
              return;
            }           
            var shipInfo = wx.getStorageSync('shipInfo');
            if(shipInfo && !shipInfo.showAddress){
              url = '/order/order/orderDetail/index?oid=' + oid + '&uid=' + app.globalData.userInfo.Uid +'&isBoss=0';
              wxpay.wxpayWm(app, oid, url, receiveCard);  //自提订单进入订单详情
            }else{
              that.getSaleInfo(that.data.cardInfo.Uid, function (count) {
                if (count > 0) {
                   //有传单礼包的路径
                  url = '/merchant/flyer/receiveLeafletCoupon/index?createUid=' + that.data.cardInfo.Uid + '&tagindex=' + tagindex + '&showWxcard=' + receiveCard;               
                }
                wxpay.wxpayWm(app, oid, url, receiveCard); 
              })
            }            
          }
        }
      }
    })
  },
  
  // 是否含有传单礼包
  getSaleInfo: function (createUid, callback) {
    wx.request({
      url: app.globalData.host + '/api/leaflet/GetPackageTotal?uid=' + app.globalData.userInfo.Uid + '&shareUid=' + createUid,
      success: function (res) {
        if (res.data.Code == 0) {
          callback(res.data.Data.StaffCount);
        } else {
          callback(0)
        }
      }
    })
  },

  initShippingAddress: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/user/GetDefaultShipAddress',
      data: {
        uid: app.globalData.userInfo.Uid
      },
      success: (res) => {
        if (res.data.Code == 0) {
          that.setData({
            curAddressData: res.data.Data
          });
          that.getDeliverySet();
        }
      }
    })
  },

  bindremark: function (e) {
    this.setData({
      remark: e.detail.value
    })
  },
  bindremark2: function (e) {
    this.setData({
      remark2: e.detail.value
    })
  },
  bindremark3: function (e) {
    this.setData({
      remark3: e.detail.value
    })
  },
  addAddress: function () {
    wx.navigateTo({
      url: "../address-add/index?said=0"
    })
  },
  selectAddress: function () {
    wx.navigateTo({
      url: "../select-address/index"
    })
  }
})
